package com.chaopei.order_mng.utils;

import com.chaopei.order_mng.entity.OrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author Corday 天涯
 * @Date 2022/5/9 17:57
 * redis数据库的应用
 */
@Component
@Slf4j
public class MyRedis {
    //类似jdbc中的connection
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //  1.1给redis数据库添加数据,此处为redis的String
    public void setString(OrderInfo order) {
        //srt= new StringRedisTemplate();
        String json = MyJson.javaToJson(order);
        //生成一个管理对象用于CURD
        ValueOperations<String, String> vo = stringRedisTemplate.opsForValue();
        //添加数据
        vo.set("order", json);
        //取消redis与java的连接
        //srt.discard();
    }

    //1.2给redis数据库添加数据,此处为redis的list
    public void setListData() {
        //生成一个管理对象用于CURD
        ListOperations<String, String> list = stringRedisTemplate.opsForList();
        OrderInfo order1 = new OrderInfo(1001, 201, "已支会", new Date());
        OrderInfo order2 = new OrderInfo(1002, 201, "未支付", new Date());
        OrderInfo order3 = new OrderInfo(1003, 202, " 未支付", new Date());
        OrderInfo order4 = new OrderInfo(1004, 202, "已支付", new Date());
        String json1 = MyJson.javaToJson(order1);
        String json2 = MyJson.javaToJson(order2);
        String json3 = MyJson.javaToJson(order3);
        String json4 = MyJson.javaToJson(order4);
        //添加数据
      long num= list.leftPushAll("orders", json1, json2,json3,json4);
      log.info("返回:"+num);
        //list.leftPushAll("orders", json1);
        //list.leftPushAll("orders", json2);
    }

    //  2.1取出redis数据库中的数据String
    public void getString() {
        //生成redis数据库操作对象
        ValueOperations<String, String> vo = stringRedisTemplate.opsForValue();
        String json = vo.get("order");
        OrderInfo order = MyJson.jsonToJava(json);
        log.info("拿到:" + order.getOrdertime());
    }
//  2.2取出redis数据库中的数据list
    public void getList() {
        //生成一个管理对象用于CURD
        ListOperations<String, String> list = stringRedisTemplate.opsForList();
        List<String> orders=list.range("orders",1,2);
        log.info(orders.toString());
    }
//    请完成其它数据类型的管理hash/set/zset
}
